package com.huakai.springenv.service;

import com.huakai.springenv.entity.po.AmountLogEntity;
import com.huakai.springenv.mapper.AmountLogMapper;
import lombok.extern.java.Log;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

@Service
@Log
public class AmountService {

    @Resource
    private AmountLogMapper amountLogMapper;


    @Transactional(isolation = Isolation.REPEATABLE_READ,rollbackFor = Exception.class)
    public void testCreateAmount() {
        log.info("start...");
        amountLogMapper.count("huakai");
        int count = amountLogMapper.countWithShareLock("huakai");
        if (count >= 0 && count < 3) {
            amountLogMapper.add(new AmountLogEntity("huakai", BigDecimal.valueOf(1)));
        } else if (count >= 3 && count <= 7) {
            amountLogMapper.add(new AmountLogEntity("huakai", BigDecimal.valueOf(2)));
        }
        LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(5));
        log.info("end...");

    }
}
